﻿/*
 * Autore: Paolo Farina
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using RecipesManager.Data;
using RecipesManager.Data.Operations;

namespace RecipesManager.MainControls.CategorySubControls
{
    /// <summary>
    /// Logica di interazione per CategoryMainPane.xaml
    /// </summary>
    public partial class CategoryMainPane : UserControl
    {

        Dictionary<string, bool> opLogSup;
        Dictionary<string, bool> opLogInf;
        ICategory _category;
        bool _editing;

        private bool _fromAnotherWindow;

        public bool FromAnotherWindow
        {
            private get { return _fromAnotherWindow; }
            set
            {
                _fromAnotherWindow = value;
                if (!_fromAnotherWindow) return;
                save_button.ToolTip = Application.Current.FindResource("AddNewCategoryTooltip");
                save_button.Content = new Image { Source = new BitmapImage(new Uri("../../Icons/document-add.png", UriKind.Relative)) };
            }
        }


        public CategoryMainPane(string id)
        {
            InitializeComponent();
            
            if (id != null && !id.Equals(""))
            {
                this.tb_nomeCategoria.Text = id;
                
                var cat = Manager.Categories[id];
                _editing = true;
                _category = cat;

                foreach (var par in cat.Parents) grid_cat_sup.Items.Add(par.Name);
                foreach (var chil in cat.Children) grid_cat_inf.Items.Add(chil.Name);
                
            }
           
            save_button.IsEnabled = false;

            UpdateInterface(id);

            agg_button_inf.IsEnabled = false;
            agg_button_sup.IsEnabled = false;
            canc_button_inf.IsEnabled = false;
            canc_button_sup.IsEnabled = false;
            opLogSup = new Dictionary<string, bool>();
            opLogInf = new Dictionary<string, bool>();

        }

        private void UpdateInterface(string id)
        {
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            
            var tmpChil = grid_cat_inf.Items.Cast<string>();
            if (_category==null) id = "";

           foreach (var ingr in Operations.GetAllIngredientsForCategory(id, tmpChil))
                    if (!grid_ingred.Items.Contains(ingr.Name)) grid_ingred.Items.Add(ingr.Name);

           var tmpPar = grid_cat_sup.Items.Cast<string>();
           tmpChil = grid_cat_inf.Items.Cast<string>(); 
            cb_catInf.Items.Clear();
            foreach (var category in Operations.GetAddableChildren(id, tmpChil, tmpPar)) if(!tmpPar.Contains(category.Name))this.cb_catInf.Items.Add(category.Name);

            tmpPar = grid_cat_sup.Items.Cast<string>();
            tmpChil = grid_cat_inf.Items.Cast<string>();
            cb_catSup.Items.Clear();
            foreach (var category in Operations.GetAddableParents(id, tmpChil, tmpPar)) if (!tmpChil.Contains(category.Name)) this.cb_catSup.Items.Add(category.Name);
            Mouse.OverrideCursor = null;
        }

        private bool Is_Modified(int ctrl)
        {
            if (ctrl==0) return true;
            if ((opLogInf!=null && opLogInf.Count > 0) || (opLogSup!=null && opLogSup.Count > 0)) return true;
            
            return false;
        }

        public bool Save()
        {

            try
            {
                if (tb_nomeCategoria.Text.Contains("Nuova categoria")) throw new Exception("Nome 'Nuova categoria...' non consentito");
                ICategory cat = null;

                if (_editing)
                    cat = Manager.Categories[_category.Name];
                else cat = Manager.Categories.Add(tb_nomeCategoria.Text);

                save_button.IsEnabled = false;

                cat.Update(tb_nomeCategoria.Text);


                foreach (var log in opLogInf)
                {
                    if (log.Value) cat.Children.Add(log.Key);
                    else cat.Children.Remove(log.Key);
                }

                foreach (var log in opLogSup)
                {
                    if (log.Value) cat.Parents.Add(log.Key);
                    else cat.Parents.Remove(log.Key);
                }
                opLogInf.Clear();
                opLogSup.Clear();
                _category = cat;
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message, "Avviso", MessageBoxButton.OK,
                                MessageBoxImage.Error);
                return false;
            }
            


            UpdateInterface(tb_nomeCategoria.Text);
            return true;
        }

        #region ButtonHandler

        void Tb_NomeCategoria_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!Is_Modified(0)) save_button.IsEnabled = false;
            else save_button.IsEnabled = true;
        }

        void Agg_Button_Click(object sender, RoutedEventArgs e)
        {
  
            if (((Button) sender).Name.EndsWith("sup"))
            {
                var selCat = (string)cb_catSup.SelectedItem;
                if (!opLogSup.ContainsKey(selCat)) opLogSup.Add(selCat, true);
                grid_cat_sup.Items.Add(selCat);                
                agg_button_sup.IsEnabled = false;
                if (!Is_Modified(2)) save_button.IsEnabled = false;
                else save_button.IsEnabled = true;
            }
            else
            {
                var selCat = (string)cb_catInf.SelectedItem;
                if (!opLogInf.ContainsKey(selCat)) opLogInf.Add(selCat, true);
                grid_cat_inf.Items.Add(selCat);             
                agg_button_inf.IsEnabled = false;
                if (!Is_Modified(1)) save_button.IsEnabled = false;
                else save_button.IsEnabled = true;
            }

            UpdateInterface(tb_nomeCategoria.Text);


        }

        void Canc_Button_Click(object sender, RoutedEventArgs e)
        {
            

            if (((Button) sender).Name.EndsWith("sup"))
            {
                var selCat = (string)grid_cat_sup.SelectedItem;
                if (!opLogSup.ContainsKey(selCat)) opLogSup.Add(selCat, false);
                else opLogSup.Remove(selCat);
                grid_cat_sup.Items.Remove(selCat);                
                if (!Is_Modified(2)) save_button.IsEnabled = false;
                else save_button.IsEnabled = true;
            }
            else
            {
                var selCat = (string)grid_cat_inf.SelectedItem;
                if (!opLogInf.ContainsKey(selCat)) opLogInf.Add(selCat, false);
                else opLogInf.Remove(selCat);
                grid_cat_inf.Items.Remove(selCat);                
                if (!Is_Modified(1)) save_button.IsEnabled = false;
                else save_button.IsEnabled = true;
            }
            UpdateInterface(tb_nomeCategoria.Text);

        }

        void Cb_cat_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox) sender).Name.EndsWith("Sup"))
            {
                if (cb_catSup.SelectedItem == null || grid_cat_sup.Items.Contains(cb_catSup.SelectedItem))
                    agg_button_sup.IsEnabled = false;
                else agg_button_sup.IsEnabled = true;
            }
            else
            {
                if (cb_catInf.SelectedItem == null || grid_cat_inf.Items.Contains(cb_catInf.SelectedItem))
                    agg_button_inf.IsEnabled = false;
                else agg_button_inf.IsEnabled = true;
            }
           
        }

        void Grid_Cat_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox) sender).Name.EndsWith("sup"))
            {
                if (grid_cat_sup.SelectedItem == null) canc_button_sup.IsEnabled = false;
                else canc_button_sup.IsEnabled = true;
            }
            else
            {
                if (grid_cat_inf.SelectedItem == null) canc_button_inf.IsEnabled = false;
                else canc_button_inf.IsEnabled = true;
            }
        }
        
        #endregion


    }
}
